
import settings from '@/common/settings.js'
const base_url = settings.baseUrl
// 请求超出时间
const timeout = 5000

// 处理未登录情况的工具函数
const handleUnauthorized = () => {
    // 清除存储的token和用户信息
    uni.removeStorageSync('token')
    // 避免重复跳转登录页
    const currentPages = getCurrentPages()
    const currentPage = currentPages[currentPages.length - 1]
    if (currentPage.route !== 'pages/login/index') {
        uni.showModal({
            title: "提示",
            content: "您的登录已过期或未登录，请重新登录",
            showCancel: false,
            success() {
                setTimeout(() => {
                    uni.navigateTo({
                        url: "/pages/login/index",
                    })
                }, 500);
            },
        });
    }
}

// 需要修改token，和根据实际修改请求头
const request = (params) => {

    const token = uni.getStorageSync('token') ?? ''
    let url = params.url;
    let method = params.method || "get";
    let data = params.data || {};
    let header = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': token ? 'Bearer ' + token : ""
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: base_url + url,
            method: method,
            header: header,
            data: data,
            timeout,
            success(response) {
                const {
                    statusCode,
                    data
                } = response
                // 根据返回的状态码做出对应的操作
                //获取成功
                if (statusCode === 200) {
                    if (data.code == 200) {
                        resolve(data.data);
                    } else {
                        uni.clearStorageSync()
                        switch (data.code) {
                            case 401:
                                handleUnauthorized();
                                break;
                            case 402:
                                uni.showToast({
                                    title: res.msg,
                                    duration: 2000,
                                })
                                break;
                            case 403:
                                handleUnauthorized();
                                break;
                            default:
                                uni.showToast({
                                    title: '请重试...',
                                    duration: 2000,
                                })
                                break;
                        }
                    }

                }
            },
            fail(err) {
                console.log(err)
                if (err.errMsg.indexOf('request:fail') !== -1) {
                    uni.showToast({
                        title: '网络异常',
                        icon: "error",
                        duration: 2000
                    })
                } else {
                    uni.showToast({
                        title: '未知异常',
                        duration: 2000
                    })
                }
                reject(err);

            },
            complete() {
                uni.hideLoading();
                uni.hideToast();
            }
        });
    }).catch(() => {});
};

export default request;